package register

import (
	"gitee.com/zaper/service-center-client/global_sign"
	"time"
)

func InitializeCenter() {
	// 阻塞获取端口，放在外面是防止放在注册里面，注册重试卡主
	port := <-global_sign.PortChan
	// 阻塞注册
	regManager := GetRegisterClientManager()
	regManager.Port = port
	regManager.AutoFlushInstanceInfo()
	leaseID, _ := retryRegister(regManager.register, 20)
	go func() {
		ticker := time.NewTicker(10 * time.Second)
		for {
			// 异步续约
			select {
			case <-ticker.C:
				leaseID, _ = regManager.keepAlive(leaseID)
			}
		}
	}()
}

func retryRegister(function func() (string, bool), delay int) (string, bool) {
	for {
		id, rt := function()
		if rt {
			return id, rt
		}
		time.Sleep(time.Duration(delay) * time.Second)
	}
}
